package com.lovelc.cn.procesor;

import com.alibaba.druid.pool.DruidDataSource;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName MyBeanProcessor
 * @Description TODO
 * @Author huangjh5
 * @Date 2021/1/4 22:29
 */
@Data
@Component(value="myBeanProcessor")
public class MyBeanProcessor implements BeanPostProcessor {

    private String dataStr;

    private boolean changeFlag = false;


    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DataSource && changeFlag) {
            DruidDataSource dataSource = new DruidDataSource();
            JsonMapper jsonMapper = new JsonMapper();
            Map<String, String> map = jsonMapper.readValue(dataStr.toString(), Map.class);
            dataSource.setUrl(map.get("dbUrl"));
            dataSource.setDriverClassName(map.get("driverName"));
            dataSource.setUsername(map.get("userName"));
            dataSource.setPassword(map.get("password"));
            dataSource.init();
            return dataSource;
        }

        return bean;
    }
}
